﻿using System.Windows;
using System.Windows.Media;

namespace Red.Controls.TimeLine.Sectors
{
    class SectorBorder : FrameworkElement
    {
        #region Private data

        private const double _penSize = 0.25;
        private Pen _cursorPen = null;

        #endregion

        static SectorBorder()
        {
            DefaultStyleKeyProperty.OverrideMetadata( typeof( SectorBorder ), new FrameworkPropertyMetadata( typeof( SectorBorder ) ) );
        }

        #region Ctr

        public SectorBorder()
        {
            _cursorPen = new Pen( (Brush)FillProperty.GetMetadata( this ).DefaultValue, _penSize );

            SnapsToDevicePixels = true;
            IsHitTestVisible = false;
        }

        #endregion

        #region Dependency properties

        public Brush Fill
        {
            get { return (Brush)GetValue( FillProperty ); }
            set { SetValue( FillProperty, value ); }
        }

        public Brush Foreground
        {
            get { return (Brush)GetValue( ForegroundProperty ); }
            set { SetValue( ForegroundProperty, value ); }
        }

        public static readonly DependencyProperty FillProperty =
            DependencyProperty.Register( "Fill", typeof( Brush ), typeof( SectorBorder ),
                new FrameworkPropertyMetadata( new SolidColorBrush( Colors.Pink ), FrameworkPropertyMetadataOptions.AffectsRender,
                    new PropertyChangedCallback( OnPenChanged ) ) );

        public static readonly DependencyProperty ForegroundProperty =
         DependencyProperty.Register( "Foreground", typeof( Brush ), typeof( SectorBorder ),
            new FrameworkPropertyMetadata( new SolidColorBrush( Colors.Black ), FrameworkPropertyMetadataOptions.AffectsRender ) );

        private static void OnPenChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
        {
            SectorBorder cursor = (SectorBorder)d;
            cursor._cursorPen = new Pen( (Brush)e.NewValue, _penSize );
        }
        
        #endregion

        protected override Size MeasureOverride( Size constraint )
        {
            if ( double.IsInfinity( constraint.Width ) || double.IsInfinity( constraint.Height ) )
            {
                return new Size( _penSize, 1 );
            }

            return new Size( _penSize, constraint.Height );
        }

        protected override Size ArrangeOverride( Size finalSize )
        {
            return finalSize;
        }

        protected override void OnRender( DrawingContext ctx )
        {
            ctx.DrawLine( _cursorPen, new Point( 0, 0 ), new Point( 0, base.ActualHeight ) );
        }       
    }
}